import traceback

from sqlalchemy import Column, String, Text, DateTime, JSON
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm.session import Session

from domain.page import Page
from eshoputils.mysql_util import DataBase

Base = declarative_base()

class SpiderResult(Base):
    # 定义表名,和数据库一致
    __tablename__ = 'spider_product_result'
    # 定义字段
    id = Column(String(32), primary_key=True)
    task_id = Column(String(32))
    platform = Column(String(32))
    crawl_type = Column(String(32))
    link = Column(Text)
    video_link = Column(Text)
    listing = Column(String(2048))
    price = Column(String(64))
    specifications = Column(JSON)
    description = Column(Text)
    extract_info = Column(JSON)
    crawl_date = Column(String(32))
    pic_paths = Column(JSON)
    target_name = Column(String(512))

    @classmethod
    def insert_product_result(cls, **kwargs):
        """
        插入task
        """
        session = Session(bind=DataBase.get_engin())
        try:
            images_injuries_task_entity = SpiderResult(**kwargs)
            session.add(images_injuries_task_entity)
            session.commit()
        except Exception as e:
            traceback.print_exc()
            session.rollback()
        finally:
            session.close()

    @classmethod
    def update_param_by_id(cls, task_id, update_param):
        """
        更新状态
        """
        session = Session(bind=DataBase.get_engin())
        try:
            session.query(SpiderResult).filter_by(id=task_id).update(update_param)
            session.commit()
        except Exception as e:
            session.rollback()
        finally:
            session.close()

    @classmethod
    def select_result(cls,task_id):
        """
        查询结果
        """
        session = Session(bind=DataBase.get_engin())
        try:
            res = session.query(SpiderResult).filter_by(id=task_id)
            return  res
        finally:
            session.close()

    @classmethod
    def select_list(cls, task_id):
        """
        查询结果
        """
        session = Session(bind=DataBase.get_engin())
        try:
            res = session.query(SpiderResult).filter_by(task_id=task_id)
            return  res
        finally:
            session.close()





